<template>
  <div class="admin-container">
    <el-row>
      <el-col :span="24">
        <el-button :disabled="buttomIsDisabled($route,'add')" type="primary" @click="handleClick(null,0,'新增管理员')">新增</el-button>
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
          <el-form
            label-position="left"
            label-width="100px"
            :model="adminForm"
            :rules="rules"
            ref="adminForm"
          >
            <el-form-item label="名称" prop="name">
              <el-input
                :disabled="formType === 1"
                v-model="adminForm.name"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
            <el-form-item label="账号" prop="username">
              <el-input
                :disabled="formType === 1"
                v-model="adminForm.username"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                :disabled="formType === 1"
                v-model="adminForm.password"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
            <el-form-item prop="status" label="启用">
              <el-switch
                :disabled="formType === 1"
                v-model="adminForm.status"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </el-form-item>
            <el-form-item label="角色" prop="newCheckRoleIds">
              <el-transfer
                v-model="adminForm.newCheckRoleIds"
                :data="roleDatas"
                :titles="['可选角色','已选角色']"
                :props="{key:'id',label: 'name'}"
              ></el-transfer>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
              v-if="formType !== 1"
              :loading="loading"
              type="primary"
              @click="confirmHandel('adminForm')"
            >确 定</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="pagination.adminDatas"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
        >
          <el-table-column type="index" width="30px"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="username" label="账号"></el-table-column>
          <el-table-column prop="password" label="密码"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '0' ? 'success' : 'danger'"
                disable-transitions
              >{{scope.row.status === '0'? '启用': '禁用'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="100px">
            <template slot-scope="scope">
              <el-button :disabled="buttomIsDisabled($route,'get')" @click="handleClick(scope.row,1,'管理员详情')" type="text" size="small">查看</el-button>
              <el-button @click="handleClick(scope.row,2,'编辑管理员')" type="text" size="small">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="pagination.pageSizeChoose"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getPaginationList,
  add,
  getDetails,
  update,
} from "@/api/admin/administrator";
import { getList } from "@/api/admin/role";

export default {
  name: "Administrator",
  created() {
    this.getPaginationSysUser();
  },
  data() {
    return {
      roleDatas: [],
      formType: 0,
      loading: false,
      pageadmins: [],
      dialogVisible: false,
      dialogTitle: "",
      adminForm: {
        name: "",
        username: "",
        password: "",
        checkRoleIds: [],
        delRoleIds: [],
        addRoleIds: [],
        status: "0",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizeChoose: [5, 10, 15, 20],
        total: 0,
        adminDatas: [],
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },

  watch: {
    dialogVisible: function () {
      if (this.dialogVisible === false) {
        this.$refs["adminForm"].resetFields();
      } else {
        getList().then((response) => {
          this.roleDatas = response.data;
        });
      }
    },
  },
  methods: {
    addAdmin() {
      add(this.adminForm)
        .then(() => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationSysUser();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updataAdmin() {
      update(this.adminForm)
        .then(() => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationSysUser();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    checkNewRoles() {
      this.adminForm.checkRoleIds.forEach((item) => {
        if (this.adminForm.newCheckRoleIds.indexOf(item) < 0) {
          this.adminForm.delRoleIds.push(item);
        }
      });
      this.adminForm.newCheckRoleIds.forEach((item) => {
        if (this.adminForm.checkRoleIds.indexOf(item) < 0) {
          this.adminForm.addRoleIds.push(item);
        }
      });
    },
    confirmHandel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType === 0) {
            this.adminForm.addRoleIds = this.adminForm.newCheckRoleIds;
            this.addAdmin();
          } else if (this.formType === 2) {
            this.checkNewRoles();
            this.updataAdmin();
          }
          this.loading = true;
        }
      });
    },
    getPaginationSysUser() {
      const params = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.currentPage,
      };
      getPaginationList(params).then((res) => {
        this.pagination.adminDatas = res.data.records;
        this.pagination.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },
    handleClick(data, type, title) {
      if (type !== 0) {
        getDetails(data.id).then((response) => {
          response.data.newCheckRoleIds = response.data.checkRoleIds;
          this.adminForm = response.data;
          this.adminForm.delRoleIds = [];
          this.adminForm.addRoleIds = [];
        });
      } else {
        this.adminForm.checkRoleIds = [];
      }
      this.dialogTitle = title;
      this.formType = type;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.menu-container {
  .el-row {
    margin-bottom: 20px;
  }
}
</style>